package one;

/**
 * You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
 * <p>
 * Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
 * Output: 7 -> 0 -> 8
 * <p>
 * ==========================================
 * <p>
 * Complexity O(m + n)
 * <p>
 * Solution:
 * <p>
 *
 * Definition for singly-linked list.
 * public class one.ListNode {
 * int val;
 * one.ListNode next;
 * one.ListNode(int x) {
 * val = x;
 * next = null;
 * }
 * }
 */

class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
        next = null;
    }
}

public class Day03_Add_Two_Numbers {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = null;
        ListNode tail = null;
        int add = 0;
        while (l1 != null || l2 != null) {
            int tmp = add;
            if (l1 != null){
                tmp += l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                tmp += l2.val;
                l2 = l2.next;
            }
            add = tmp / 10;
            tmp = tmp % 10;
            ListNode node = new ListNode(tmp);
            if (head == null) {
                head = node;
                tail = node;
            } else {
                tail.next = node;
                tail = tail.next;
            }
        }
        if (add != 0) {
            ListNode node = new ListNode(add);
            tail.next = node;
        }
        return head;
    }
}
